//
//  WeatherApi.swift
//  网络请求接口包装类
//  对外部提供一个和框架无关的接口
//
//  Created by smile on 2020/10/22.
//

import Foundation

//导入响应式编程框架
import RxSwift

//导入JSON解析框架
import HandyJSON

//导入网络框架
import Moya

class WeatherApi {
    /// 单例设计模式
    /// 饿汉式单例
    static let shared = WeatherApi()
    
    /// MoyaProvider
    private let provider:MoyaProvider<WeatherService>!
    
    /// 私有构造方法
    private init() {
        //插件列表
        var plugins:[PluginType] = []
        
        
        var configuration=NetworkLoggerPlugin.Configuration()
        configuration.logOptions=[NetworkLoggerPlugin.Configuration.LogOptions.successResponseBody]
        
//        if DEBUG {
            //表示当前是调试模式
            //添加网络请求日志插件
            plugins.append(NetworkLoggerPlugin(configuration: configuration))
//        }
        
        provider = MoyaProvider<WeatherService>(plugins: plugins)
    }
    
    /// 实时天气
    ///
    /// - Parameter id: <#id description#>
    /// - Returns: <#return value description#>
    func realtime(lat:Double,lng:Double) -> Observable<RealtimeResponse> {
        return provider
            .rx
            .request(.realtime(lat: lat,lng: lng))
            .filterSuccessfulStatusCodes()
            .asObservable()
            .mapString()
            .mapObject(RealtimeResponse.self)
    }
    
    /// 通用天气
    ///
    /// - Parameter id: <#id description#>
    /// - Returns: <#return value description#>
    func weather(lat:Double,lng:Double) -> Observable<WeatherResponse> {
        return provider
            .rx
            .request(.weather(lat: lat,lng: lng))
            .filterSuccessfulStatusCodes()
            .asObservable()
            .mapString()
            .mapObject(WeatherResponse.self)
    }
    
    
    /// 搜索区域
    ///
    /// - Parameter id: id description
    /// - Returns: <#return value description#>
    func place(data:String) -> Observable<PlaceResponse> {
        return provider
            .rx
            .request(.place(data:data))
            .filterSuccessfulStatusCodes()
            .asObservable()
            .mapString()
            .mapObject(PlaceResponse.self)
    }
//    /// 未来天气
//    ///
//    /// - Parameter id: <#id description#>
//    /// - Returns: <#return value description#>
//    func daily(lat:Double,lng:Double) -> Observable<DailyResponse> {
//        return provider
//            .rx
//            .request(.daily(lat: lat,lng: lng))
//            .filterSuccessfulStatusCodes()
//            .asObservable()
//            .mapString()
//            .mapObject(DailyResponse.self)
//    }
}
